import * as express from 'express';
import * as path from 'path';

import {Server} from 'ws';

const app = express();
app.use('/',express.static(path.join(__dirname,'..','client')));

app.get('/api/stock', (req, res) => {
    let result = stocks;
    let params = req.query;
    if(params.name){
        result = result.filter(stock=>stock.name.indexOf(params.name) !==-1)
    }
    res.json(result);
});
app.get('/api/stock/:id', (req, res) => {
    res.json(stocks.find(stock=>stock.id == req.params.id));
});

const server = app.listen(8000,'localhost',()=>{
    console.log('服务器已经启动，地址http://localhost:8000')
})

const wsServer = new Server({port:8001});

let subScriptions = new Set<any>();

wsServer.on('connection',websocket=>{
    subScriptions.add(websocket);
})
let messageCount = 0
setInterval(()=>{
    subScriptions.forEach(ws=>{
        
        if(ws.readyState === 1){
            ws.send(JSON.stringify({messageCount:messageCount++}))
        }else{
            subScriptions.delete(ws);
        }
    })
},2000)

export class Stock {
    constructor(public id: number,
        public name: string,
        public price: number,
        public rating: number,
        public desc: string,
        public categories: Array<string>) {
    }
};


let stocks: Stock[] = [
    new Stock(1, 'IBM', 13.2, 0, 'IBM股票', ['IT', '互联网']),
    new Stock(2, '二六三', 13.2, 1, '二六三股票', ['能源', '互联网']),
    new Stock(3, '伊利', 13.2, 2, '伊利股票', ['IT', '交通']),
    new Stock(4, '南车', 13.2, 3, '南车股票', ['IT', '交通']),
    new Stock(5, '北车', 13.2, 4, '北车股票', ['医疗', '互联网']),
    new Stock(6, '中车', 13.2, 5, '中车股票', ['教育', '互联网']),
    new Stock(7, 'UKEC', 13.2, 4, 'UKEC股票', ['教育', '互联网']),
];